<?php
declare (strict_types = 1);

namespace app\tools;

use app\exception\LogicException;
use app\facade\CurlFacade;
use Exception;
use think\App;

final class AppletsTool
{
    private $appID;
    private $secret;
    // private $access_token;

    private $url = "https://api.weixin.qq.com";

    /**
     * WechatTool constructor.
     * @throws Exception
     */
    public function __construct()
    {
        $this->appID = config('wechat.applets_app_id');
        $this->secret = config('wechat.applets_app_secret');
        // $this->access_token = $this->getAccessToken();
        // Log::debug('微信请求debug:app_secret: {app_secret}, app_id: {app_id}, access_token: {access_token}', [
        //     'app_id' => $this->appID,
        //     'app_secret' => $this->secret,
        //     'access_token' => $this->access_token,
        // ]);
    }

    /**
     * 获取&缓存access_token
     *
     * @return mixed|object|App
     * @throws Exception
     */
    public function getAccessToken()
    {
        if (cache('applet_access_token')) {
            return cache('applet_access_token');
        } else {
            $url = "$this->url/cgi-bin/token?grant_type=client_credential&appid=$this->appID&secret=$this->secret";
            $response = json_decode(CurlFacade::curlGET($url), true);

            if (isset($response['errcode']) && 0 != $response['errcode']) {
                throw new LogicException($response['errmsg'], $response['errcode']);
            }

            cache("cache('applet_access_token')", $response['access_token'], [
                // 'expire' => $response['expires_in']
                'expire' => 5400
            ]);

            return $response['access_token'];
        }
    }

    /**
     * 登录凭证校验
     *
     * @param $code
     * @return mixed
     * @throws LogicException
     */
    public function code2Session($code)
    {
        $url = "$this->url/sns/jscode2session?appid=$this->appID&secret=$this->secret&js_code=$code&grant_type=authorization_code";
        $response = json_decode(CurlFacade::curlGET($url), true);

        if (isset($response['errcode']) && 0 != $response['errcode']) {
            throw new LogicException($response['errmsg'], $response['errcode']);
        }

        return $response;
    }

    /**
     * 解析微信用户手机加密数据
     *
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @return mixed
     * @throws LogicException
     */
    public function decryptPhoneData($sessionKey, $encryptedData, $iv)
    {
        $aesKey = base64_decode($sessionKey);

        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        if (!$result) {
            throw new LogicException(lang('communal.wechat user mobile error'));
        }

        return json_decode($result, true);
    }

    /**
     * 小程序码
     *
     * @param $params
     * @return mixed
     * @throws LogicException
     */
    public function getwxacodeunlimit($params)
    {
        $url = "$this->url/wxa/getwxacodeunlimit?access_token=" . $this->getAccessToken();
        $result = CurlFacade::curlPost($url, json_encode($params));
        $response = json_decode($result, true);

        if (isset($response['errcode']) && 0 != $response['errcode']) {
            throw new LogicException($response['errmsg'], $response['errcode']);
        }

        return $result;
    }

    /**
     * 统一发送消息
     *
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function uniform_send($params)
    {
        $url = "{$this->url}/cgi-bin/message/wxopen/template/uniform_send?access_token=" . $this->getAccessToken();
        $result = CurlFacade::curlPost($url, json_encode($params));
        $response = json_decode($result, true);

        if (isset($response['errcode']) && 0 != $response['errcode']) {
            throw new LogicException($response['errmsg'], $response['errcode']);
        }

        return $response;
    }

    /**
     * 简封账号操作通知公众号推送(UII9GJXwuE8AGalyS8ItEvFTA6M3g6j9YuqIgF1kZX0)
     *
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function build_uniform_send_msg1($params)
    {
        list($toUser, $first, $keyword1, $remark) = $params;
        // 小程序
        $appletsAppID = config('wechat.applets_app_id');
        // 公众号
        $publicAppId = config('wechat.public_app_id');
        $publicTemplateId = config('wechat.public_template_id');

        return $this->uniform_send([
            'touser' => $toUser,
            'mp_template_msg' => [
                'appid' => $publicAppId,
                'template_id' => $publicTemplateId,
                'url' => '',
                'miniprogram' => [
                    'appid' => $appletsAppID,
                    'pagepath' => '',
                ],
                'data' => [
                    'first' => [
                        'value' => $first,
                        'color' => '#173177',
                    ],
                    'keyword1' => [
                        'value' => $keyword1,
                        'color' => '#173177',
                    ],
                    'remark' => [
                        'value' => $remark,
                        'color' => '#173177',
                    ],
                ],
            ],
        ]);
    }
}
